package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class SocketXiaoze {
	private static String url = "http://www.xiaozeav.com/html/article/index";//http://www.xxx83.com/
	private static int number = 102;

	public static void download(int num, String href, String title) {
		URL url;
		try {
			// BufferedReader reader = new BufferedReader(new
			// InputStreamReader(
			// conn.getInputStream()));
			File dir = new File("E:/3/" + num + title);
			if (!dir.exists())
				dir.mkdirs();
			File file = new File(dir.getAbsolutePath().trim() + "/"
					+ System.currentTimeMillis() + ".jpg");
			url = new URL(href);
			// URLConnection conn = url.openConnection();
			InputStream in = url.openStream();
			BufferedInputStream bufIn = new BufferedInputStream(in);
			BufferedOutputStream bufOut = new BufferedOutputStream(
					new FileOutputStream(file));
			byte[] b = new byte[1];
			while (bufIn.read(b) != -1) {
				bufOut.write(b);
			}
			bufOut.flush();
			bufOut.close();
			bufIn.close();

		} catch (Exception e) {
		}
	}

	public static void main(String[] args) {
		while (true) {
			String urlStr = url + number + ".html";
			String tempContent = getDocumentAt(urlStr);
			String title = Util.getMatchString(tempContent, "<title>",
					"</title>");
			if (title == null)
				return;
			title = title.split("-")[0].substring(7);
			int l = 0;
			l = tempContent.indexOf("<div class=\"title\">");
			String tempStr = tempContent.substring(l);
			l = tempStr.indexOf("<div class=\"content\">");
			tempStr = tempStr.substring(0, l);
			List<String> list0 = Util.getMatchList(tempStr, "src=\"", "\"");
			System.out.println("开始" + number);
			for (int i = 0; i < list0.size(); i++) {
				urlStr = list0.get(i).substring(5);
				urlStr = urlStr.substring(0, urlStr.length() - 1);
				download(number, urlStr, title);
			}
			number = number + 1;
		}
	}

	public static String getDocumentAt(String urlString) {
		StringBuffer document = new StringBuffer();
		try {
			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "GBK"));
			String line = null;
			while ((line = reader.readLine()) != null)
				document.append(line + "\n");
			reader.close();

		} catch (MalformedURLException e) {
			System.out.println("Unable to connect to URL: " + urlString);
		} catch (IOException e) {
			System.out.println("IOException when connecting to URL: "
					+ urlString);
		}
		return document.toString();
	}
}
